<template>
  <div class="categories-container">
    <div class="categories-header">
      <h1>分类管理</h1>
      <div class="header-actions">
        <RadioGroup v-model:value="activeTab" class="tab-selector">
          <Radio value="income">收入分类</Radio>
          <Radio value="expense">支出分类</Radio>
        </RadioGroup>
        <Button type="primary" @click="showAddModal = true">
          <IconPlus class="mr-2" />
          添加分类
        </Button>
      </div>
    </div>
    
    <!-- 分类列表 -->
    <div class="categories-list">
      <div v-if="activeCategories.length === 0" class="empty-state">
        <p>暂无{{ activeTab === 'income' ? '收入' : '支出' }}分类</p>
        <Button type="primary" @click="showAddModal = true" class="mt-4">
          添加第一个分类
        </Button>
      </div>
      
      <div v-else class="categories-grid">
        <div 
          v-for="category in activeCategories" 
          :key="category.id"
          class="category-card"
        >
          <div class="category-info">
            <div class="category-name">{{ category.name }}</div>
            <div class="category-type">
              {{ category.type === 'income' ? '收入' : '支出' }}
            </div>
          </div>
          
          <div class="category-actions">
            <Button 
              size="small" 
              type="text" 
              @click="handleEdit(category)"
              icon="icon-edit"
            >
              编辑
            </Button>
            <Button 
              size="small" 
              type="text" 
              danger
              @click="handleDelete(category.id)"
              icon="icon-delete"
            >
              删除
            </Button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 添加分类模态框 -->
    <Modal 
      v-model:visible="showAddModal" 
      title="添加分类" 
      @ok="handleAddCategory"
      @cancel="handleCancelAdd"
    >
      <div class="modal-form">
        <Form v-model:model="newCategory" :rules="categoryRules" ref="addFormRef">
          <FormItem label="分类名称" field="name">
            <Input 
              v-model:value="newCategory.name" 
              placeholder="请输入分类名称"
              :maxlength="20"
              show-word-limit
            />
          </FormItem>
          
          <FormItem label="分类类型" field="type">
            <RadioGroup v-model:value="newCategory.type">
              <Radio value="income">收入</Radio>
              <Radio value="expense">支出</Radio>
            </RadioGroup>
          </FormItem>
        </Form>
      </div>
    </Modal>
    
    <!-- 编辑分类模态框 -->
    <Modal 
      v-model:visible="showEditModal" 
      title="编辑分类" 
      @ok="handleUpdateCategory"
      @cancel="handleCancelEdit"
    >
      <div class="modal-form">
        <Form v-model:model="editCategory" :rules="categoryRules" ref="editFormRef">
          <FormItem label="分类名称" field="name">
            <Input 
              v-model:value="editCategory.name" 
              placeholder="请输入分类名称"
              :maxlength="20"
              show-word-limit
            />
          </FormItem>
          
          <FormItem label="分类类型" field="type">
            <RadioGroup v-model:value="editCategory.type">
              <Radio value="income">收入</Radio>
              <Radio value="expense">支出</Radio>
            </RadioGroup>
            <div class="form-hint">注意：修改类型可能影响历史交易数据</div>
          </FormItem>
        </Form>
      </div>
    </Modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useFinanceStore, type Category } from '../store/finance';
import { 
  Button, 
  Modal, 
  Form, 
  FormItem, 
  Input, 
  RadioGroup, 
  Radio 
} from '@arco-design/web-vue';
import { IconPlus } from '@arco-design/web-vue/es/icon';

const financeStore = useFinanceStore();

// 状态管理
const activeTab = ref<'income' | 'expense'>('income');
const showAddModal = ref(false);
const showEditModal = ref(false);
const addFormRef = ref<Form>();
const editFormRef = ref<Form>();
const currentEditId = ref<string>('');

// 表单数据
const newCategory = ref<Omit<Category, 'id'>>({
  name: '',
  type: 'income'
});

const editCategory = ref<Category>({
  id: '',
  name: '',
  type: 'income'
});

// 表单验证规则
const categoryRules = {
  name: [{
    required: true,
    message: '请输入分类名称',
    trigger: 'blur'
  }, {
    min: 2,
    max: 20,
    message: '分类名称长度应在2-20个字符之间',
    trigger: 'blur'
  }],
  type: [{
    required: true,
    message: '请选择分类类型',
    trigger: 'change'
  }]
};

// 计算属性：根据当前标签页筛选分类
const activeCategories = computed(() => {
  return financeStore.categories.filter(cat => cat.type === activeTab.value);
});

// 方法：处理编辑
const handleEdit = (category: Category) => {
  currentEditId.value = category.id;
  editCategory.value = { ...category };
  showEditModal.value = true;
};

// 方法：处理删除
const handleDelete = (id: string) => {
  // 检查是否有交易记录使用了该分类
  const hasTransactions = financeStore.transactions.some(t => t.category === id);
  
  if (hasTransactions) {
    Modal.confirm({
      title: '确认删除',
      content: '该分类下有交易记录，删除后这些记录的分类将变为未知。确定要删除吗？',
      onOk: () => {
        // 实际项目中可能需要先处理相关交易记录
        Modal.warning({
          title: '提示',
          content: '为了保证数据完整性，系统暂不允许删除有交易记录的分类。',
          onOk: () => {}
        });
      }
    });
  } else {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个分类吗？',
      onOk: () => {
        // 实际项目中可以删除分类
        Modal.warning({
          title: '提示',
          content: '为了保证数据完整性，系统暂不允许删除预设分类。',
          onOk: () => {}
        });
      }
    });
  }
};

// 方法：处理添加分类
const handleAddCategory = async () => {
  if (addFormRef.value) {
    const valid = await addFormRef.value.validate();
    if (valid) {
      financeStore.addCategory(newCategory.value);
      handleCancelAdd();
    }
  }
};

// 方法：处理更新分类
const handleUpdateCategory = async () => {
  if (editFormRef.value) {
    const valid = await editFormRef.value.validate();
    if (valid) {
      // 实际项目中可以更新分类
      Modal.success({
        title: '成功',
        content: '分类更新成功！',
        onOk: () => {
          handleCancelEdit();
        }
      });
    }
  }
};

// 方法：取消添加
const handleCancelAdd = () => {
  addFormRef.value?.resetFields();
  newCategory.value = {
    name: '',
    type: 'income'
  };
  showAddModal.value = false;
};

// 方法：取消编辑
const handleCancelEdit = () => {
  editFormRef.value?.resetFields();
  showEditModal.value = false;
};

// 组件挂载时初始化数据
onMounted(() => {
  financeStore.loadFromLocalStorage();
});
</script>

<style scoped>
.categories-container {
  padding: 24px;
}

.categories-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  flex-wrap: wrap;
  gap: 16px;
}

.categories-header h1 {
  font-size: 24px;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

.tab-selector {
  background-color: var(--color-bg-2);
  border-radius: 4px;
  padding: 4px;
}

.categories-list {
  background-color: var(--color-bg-2);
  border-radius: 8px;
  padding: 24px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: var(--color-text-secondary);
}

.categories-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}

.category-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background-color: var(--color-bg-1);
  border: 1px solid var(--color-border);
  border-radius: 8px;
  transition: all 0.3s;
}

.category-card:hover {
  box-shadow: var(--shadow-2);
  transform: translateY(-2px);
}

.category-info {
  flex: 1;
}

.category-name {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 4px;
}

.category-type {
  font-size: 14px;
  color: var(--color-text-secondary);
}

.category-actions {
  display: flex;
  gap: 8px;
}

.modal-form {
  max-height: 400px;
  overflow-y: auto;
}

.form-hint {
  color: var(--color-text-secondary);
  font-size: 12px;
  margin-top: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .categories-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .header-actions {
    flex-direction: column;
    align-items: stretch;
  }
  
  .categories-grid {
    grid-template-columns: 1fr;
  }
  
  .category-card {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .category-actions {
    justify-content: flex-end;
  }
}
</style>